"""This module provides mydouyn"""
import time
import json
import os
import platform
import datetime
from playwright.sync_api import sync_playwright
from playwright.sync_api import Page
from auto.sleep.data import go_to_sleep
from auto.sleep.data import get_pitcute
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger

########################################################################
class CMyCsdn:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """
    def __init__(self,cookies_path: str, login_url: str, upload_picture_url: str, upload_mp4_url: str):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.upload_picture_url = upload_picture_url
        self.upload_mp4_url = upload_mp4_url
        # playwright 部分
        self.browser = None
        print("create CMyCsdn")

    def __del__(self):
        print("CMyCsdn is being destroyed")

    def upload_msg_with_picture(self, picture_path: str, habit_name:str, habit_detail:str):
        """
          upload_picture
        """
        with sync_playwright() as playwright:
            display_headless = False
            sys = platform.system()
            if sys == "Linux":
                display_headless = True
            self.browser = playwright.chromium.launch(channel="chrome",headless=display_headless)
            login_page = self.login_or_restore_cookies()
            self.msg_up_load(login_page, picture_path, habit_name,habit_detail)
            self.browser.close()

    def login_or_restore_cookies(self) -> Page:
        """
          登录 context-->page
        """
        userAgent ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
        sys = platform.system()
        if sys == "Linux":
            userAgent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
        
        context = self.browser.new_context(user_agent=userAgent)
        context.clear_cookies()
        page = context.new_page()
        page.goto(self.login_url)

        if os.path.exists(self.cookies_path):
            print("load cookies")
            # 从文件中加载 cookies
            with open(self.cookies_path, 'r',encoding='utf-8') as f:
                cookies = json.load(f)
            context.add_cookies(cookies)
            time.sleep(3)
        else:
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            time.sleep(80)
            cookies = page.context.cookies()
            with open(self.cookies_path, 'w',encoding='utf-8') as f:
                f.write(json.dumps(cookies))
        print("login_or_restore_cookies")
        return page

    def msg_up_load(self, page: Page, picture_path: str,habit_name:str, habit_detail:str):
        """
        msg_up_load
        """
        page.goto(self.upload_picture_url)
        time.sleep(3)
        print(f"open  {self.upload_picture_url}")
        
        msg = habit_name + "\r\n"
        msg += habit_detail
        # 博客内容
        ##  playwright codegen https://blink.csdn.net/?spm=1010.2135.3001.5353
        page.get_by_placeholder("有什么新的观点，快来说说看～").fill(msg)

        page.mouse.down()
        page.mouse.down()
        page.mouse.down()
        page.wait_for_timeout(2000)
        # bug 
        if len(picture_path) > 0:
            for onefile in picture_path:
                with page.expect_file_chooser() as fc_info:
                     #page.locator(".emoticon").first.click()
                     page.locator("//span[contains(@class, 'emoticon icon-picture')]").first.click()
                page.wait_for_timeout(1000)
                file_chooser = fc_info.value
                file_chooser.set_files(onefile)
                time.sleep(10)
                print(f"open  {onefile}")
 
        print("up load pic ok")
        page.get_by_role("contentinfo").get_by_text("发布", exact=True).click()
        print("发布")
        time.sleep(6)

def interface_auo_upload_mycsdn(file_path,habit_name,habit_detail):
    """
      对外调用接口
    """
    try:
        sys = platform.system()
        login_url = "https://www.csdn.net/"
        upload_picture_url = "https://blink.csdn.net/?spm=1020.2143.3001.5353"
        upload_mp4_url = "https://blink.csdn.net/?spm=1020.2143.3001.5353"
        if sys == "Windows":
            cookies_path = r"D:\mp4\etc\mycsdn_small.json"
        elif sys == "Darwin":
             cookies_path = r"/Users/wangchuanyi/mp4/etc/mycsdn_small.json"
        else:
            cookies_path = r"/root/bin/mycsdn_small.json"
        autoupload = CMyCsdn(cookies_path, login_url, upload_picture_url,upload_mp4_url)
        autoupload.upload_msg_with_picture(file_path, habit_name,habit_detail)
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
###################################################
def future_for_sleep():
    """
      每天写50字产品理解输出，10行代码
    """
    habit_detail = go_to_sleep.interface_go_to_sleep()
    random_images = get_pitcute.interface_get_three_pic()
    habit_name = "21点远离手机提醒"
    # 格式化为 年-月-日
    formatted_date = datetime.datetime.now().strftime('%Y-%m-%d')
    habit_name = formatted_date + " " + habit_name

    try:
        interface_auo_upload_mycsdn(random_images, habit_name, habit_detail)
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
if __name__ == '__main__':
    print("test")
    # playwright codegen https://blink.csdn.net/?spm=1010.2135.3001.5353
    future_for_sleep()
    job_defaults = {
        'coalesce': False,
        'max_instances': 1
    }
    future_for_sleep()
    # 调度器组件
    backsched = BlockingScheduler(job_defaults=job_defaults, timezone='Asia/Shanghai')
    # future_for_sleep callable函数 习惯养成--早睡早起
    # crontab 是 Linux 系统中用于设置周期性被执行的指令的命令
    # 0 0 * * *	每天的午夜（0 点）执行一次
    backsched.add_job(future_for_sleep, CronTrigger.from_crontab("0 21 * * *"), id="get_up")
    backsched.start()